package cn.bigfire.wzdj.util;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import lombok.extern.slf4j.Slf4j;

/**

 <!-- jprotobuf -->
 <dependency>
 <groupId>com.baidu</groupId>
 <artifactId>jprotobuf</artifactId>
 <version>2.4.20</version>
 </dependency>

 */
@Slf4j
public class JProtobufUtil {
    /**
     * 序列化
     *
     * @param obj
     * @return
     */
    public static <T> byte[] serializer(T obj) {
        try {
            Class clazz = (Class<T>) obj.getClass();
            Codec<T> codec = ProtobufProxy.create(clazz);
            return codec.encode(obj);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    /**
     * 反序列化
     *
     * @param data
     * @param clazz
     * @return
     */
    public static <T> T deserializer(byte[] data, Class<T> clazz) {
        try {
            Codec<T> codec = ProtobufProxy.create(clazz);
            return codec.decode(data);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new IllegalStateException(e.getMessage(), e);
        }
    }


}
